#include <iostream>
#include <string>
#include <utility>
#include <unistd.h>
#include <pthread.h>
#include <mysql/mysql.h>
#include "comm.hpp"

class Mysql
{
private:
    MYSQL* _conn;
    static Mysql* _mysql;

    const char* HOST = "127.0.0.1";
    const char* USER = "http_client";
    const char* PASSWD = "http";
    const char* DB = "http";
    const int   PORT = 3306;

    Mysql()
    {
        _conn = mysql_init(nullptr);
        if (mysql_real_connect(_conn, HOST, USER, PASSWD, DB, PORT, nullptr, 0) == nullptr) {
            std::cerr << "mysql connect failed\n";
            exit(1);
        }

        mysql_set_character_set(_conn, "utf8");
    }

public:
    static Mysql* GetInstance()
    {
        pthread_mutex_t lck = PTHREAD_MUTEX_INITIALIZER;
        if (_mysql == nullptr)
        {
            pthread_mutex_lock(&lck);
            if (_mysql == nullptr)
                _mysql = new Mysql();
            pthread_mutex_unlock(&lck);
        }
        return _mysql;
    }

    ~Mysql()
    {
        mysql_close(_conn);
    }

    bool ExecuteSql(std::string& sql)
    {
        if (mysql_query(_conn, sql.c_str()) != 0)
        {
            std::cerr << "sql: " << sql << " failed\n";
            return false;
        }
        std::cerr << "sql: " << sql << " success\n";
        return true;
    }

};
Mysql* Mysql::_mysql = nullptr;

bool Insert(std::string& query)
{
    std::string name;
    std::string passwd;
    CutString(query, &name, &passwd, "&");
    //name=lisa passwd=1234
    CutString(name, nullptr, &name, "=");
    CutString(passwd, nullptr, &passwd, "=");

    std::string sql = "insert into user (name, password) values ('" + name + "', '" + passwd + "');";
    return Mysql::GetInstance()->ExecuteSql(sql);
}

int main()
{
    std::string query = GetQuery();
    Insert(query);

    std::cout << R"(<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8">)"
        << "<title>登录/注册</title>"
        << R"(<link rel="shortcut icon" href="favicon.ico" />)"
        << R"(<link rel="apple-touch-icon" href="favicon.ico" />)"
        << "</head><body>"
        << R"(<br>)"
        << R"(<a href="/">首页 </a>)"
        << R"(<a href="/login.html">登录注册 </a>)"
        << R"(<a href="/shell.html">远程连接 </a><br>)"
        << "<h2>登录结果</h2><br>"
        << "<h2>"
        << (Insert(query) ? "登录成功！</h2>" : "注册成功</h2>！");
    std::cout << "</body></html>" << std::endl;

    return 0;
}
